<?php
namespace Admin\Controller;
use Think\Controller;

class LoginController extends Controller
{
    //后台管理员的页面和登录处理
    public function index()
    {
        if (IS_POST)
        {
            $where["name"] = trim(I('post.name'));
            $manager = M('manager')->where($where)->find();
            if($manager) {
                if($manager["shop_id"] != 0){
                    $this->error("不存在此账号" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                if($manager["m_status"] != 1){
                    $this->error("您的账号已被关闭" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                $pwd = trim(I('post.password'));
                $password = md5(md5($pwd) .$manager["salt"] );

                if($password !== $manager["password"]){
                    $this->error("密码错误" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                $role = D("RoleView")->where("manager.id = %d" ,array($manager["id"]))->find();
                if(!$role){
                    $this->error("管理员未给您分配角色" ,$_SERVER['HTTP_REFERER'] ,1);
                }
                // 登陆成功
                session('manager_id' ,$manager['id']);
                session("shop_id",$manager['shop_id']);
                session('role_id' ,$role['role_id']);
                session('avatar' ,$role['avatar']);
                session('name' ,$role['user_name']);
                session('mobile' ,$role['mobile']);
                session("role_name" ,$role['role_name']);
                M("manager")->where("id = ".$manager["id"])->save(array("last_login" => time(),"last_ip" => get_client_ip()));
                $this->redirect('Index/index');
            }else{
                $this->error("用户名错误" ,$_SERVER['HTTP_REFERER'] ,1);
            }
        } else {
//            order_auto_receipt();
            //如果已经登录则跳转到后台首页
//            if (session('?manager_id')) $this->redirect('Index/index');
            if (session('shop_id')=="0"){
                $this->redirect('Index/index');
            }
            $this->display();
        }
    }

    // 清除 runtime 缓存
    public function clearcache()
    {
        deldir ( RUNTIME_PATH );
        $this->ajaxReturn(array("status" => "success"));
    }

    //管理员退出登录
    public function logout()
    {
        session('manager_id' ,null);
        session("shop_id",null);
        session('role_id' ,null);
        session('avatar' ,null);
        session('name' ,null);
        session('mobile' ,null);
        session("role_name" ,null);
        cookie(null);
        $this->redirect('Login/index');
    }

}